package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageHotel;
import cn.itcast.hotel.pojo.RequestParameter;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {



    @Autowired
    private RestHighLevelClient client;


    //从索引库中将数据取出
    @Override
    public PageHotel getHotel(RequestParameter parameter) {
        try {
            SearchRequest request = new SearchRequest("hotel");
            String key = parameter.getKey();
            if (StringUtils.isEmpty(key)) {
                request.source().query(QueryBuilders.matchAllQuery());
            } else {
                request.source().query(QueryBuilders.matchQuery("all", key));
            }
            Integer page = parameter.getPage();
            Integer size = parameter.getSize();
            request.source().from((page - 1) * size).size(size);

            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            return getPageHotel(search);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PageHotel getFiltersHotel(RequestParameter parameter) {
        SearchRequest request = new SearchRequest("hotel");
        //创建布尔查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //添加must条件
        String key = parameter.getKey();
        if (StringUtils.isEmpty(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //添加filter条件
        String brand = parameter.getBrand();
        if (!StringUtils.isEmpty(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        String city = parameter.getCity();
        if (!StringUtils.isEmpty(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        String starName = parameter.getStarName();
        if (!StringUtils.isEmpty(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        Integer minPrice = parameter.getMinPrice();
        Integer maxPrice = parameter.getMaxPrice();
        if (maxPrice != null && minPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                            QueryBuilders.termQuery("isAD", true),
                            ScoreFunctionBuilders.weightFactorFunction(36934)
                    )
                });


        request.source().query(functionScoreQueryBuilder);

        Integer page = parameter.getPage();
        Integer size = parameter.getSize();
        request.source().from((page - 1) * size).size(size);

        String location = parameter.getLocation();
        //location = "31.0348435427574,121.61209140377429";
        if (!StringUtils.isEmpty(location)) {
            request.source().sort(SortBuilders.geoDistanceSort(
                    "location", new GeoPoint(location))
            .order(SortOrder.ASC)
            .unit(DistanceUnit.KILOMETERS));
        }

        SearchResponse search = null;
        try {
            search = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PageHotel pageHotel = getPageHotel(search);

        return pageHotel;
    }

    private PageHotel getPageHotel(SearchResponse search) {
        //解析searchResponse
        SearchHits searchHits = search.getHits();
        PageHotel pageHotel = new PageHotel();
        if (searchHits != null) {
            long value = searchHits.getTotalHits().value;
            pageHotel.setTotal(value);
        }
        SearchHit[] hits = searchHits.getHits();
        List<HotelDoc> hotelDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);

            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                hotelDoc.setDistance(sortValues[0]);
            }

            hotelDocs.add(hotelDoc);
        }
        pageHotel.setHotels(hotelDocs);
        return pageHotel;
    }
}
